package controllers;

import java.util.ArrayList;
import java.util.LinkedList;

import org.w3c.dom.ls.LSInput;

import models.Unit;
import models.User;
import play.data.validation.Required;
import play.mvc.Controller;
import play.mvc.With;

@With(Secure.class)
public class Units extends Controller {

	public static void AddUnit(@Required String UnitCode,
			@Required String UnitPrice, @Required String UnitLength,
			@Required String UnitWidth, @Required String UnitStatus,
			@Required String DeliveryDate) {

		if (!validation.hasErrors()) {

			ArrayList<Unit> listunit = (ArrayList) Unit.findAll();
			for (int i = 0; i < listunit.size(); i++) {
				if (listunit.get(i).UnitCode.equals(UnitCode)) {
					flash.error("oops the unit code is used before . please change it");
					render();
				}
			}
			LinkedList<String> attributes = new LinkedList();
			attributes.addLast(UnitCode);
			attributes.addLast(UnitPrice);
			attributes.addLast(UnitLength);
			attributes.addLast(UnitWidth);
			attributes.addLast(UnitStatus);
			attributes.addLast(DeliveryDate);

			Unit unit = new Unit(attributes);
			unit.save();
			CreatedUnit(unit);

		} else {
			render();
		}

	}

	public static void DeleteUnit(long id) {
		Unit unit = Unit.findById(id);
		unit.delete();
		ViewAllUnits();
	}

	public static void CreatedUnit(Unit unit) {
		render(unit);
	}

	public static void ViewAllUnits() {
		ArrayList<Unit> unitlist = (ArrayList) Unit.findAll();
		render(unitlist);
	}

	public static void ViewUnit(long id) {
		Unit x = Unit.findById(id);
		render(x);
	}

	public static void EditUnit(long id) {
		Unit x = Unit.findById(id);
		System.out.println("X UnitCode is " + x.UnitCode);

		render(x, id);

	}

	public static void Assign(Long userid, Long unitid) {

		if (userid != null) {
			System.out.println("xxxxxxxxxxxxx " + userid + "ooooooooooo "
					+ unitid);
			User user = User.findById(userid);
			Unit unit = Unit.findById(unitid);
			user.units.add(unit);
			unit.users.add(user);
			unit.save();
			user.save();
			Assigned(userid, unitid);
		} else {
			AssignUnit();
		}
	}

	public static void Assigned(Long userid, Long unitid) {

		User user = User.findById(userid);
		Unit unit = Unit.findById(unitid);
		render(user, unit);

	}

	public static void AssignUnit() {

		render();

	}

	public static void Edit(long id, String UnitCode, String UnitPrice,
			String UnitLength, String UnitWidth, String UnitStatus,
			String DeliveryDate) {
		if (UnitCode != null) {
			Unit x = Unit.findById(id);
			x.UnitCode = UnitCode;
			x.UnitPrice = UnitPrice;
			x.UnitLength = UnitLength;
			x.UnitWidth = UnitWidth;
			x.UnitStatus = UnitStatus;
			x.DeliveryDate = DeliveryDate;
			x.save();
			ViewUnit(id);
		} else {
			EditUnit(id);
		}
	}

}
